package com.wyx.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wyx.entity.Admin;
import com.wyx.entity.Student;
import com.wyx.entity.Teacher;
import com.wyx.service.AdminService;
import com.wyx.service.StudentService;
import com.wyx.service.TeacherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private StudentService ss;
    @Autowired
    private TeacherService ts;
    @Autowired
    private AdminService as;

    @GetMapping("/login")
    public boolean login(String name, String pwd, int role, HttpSession session){
        Object one=null;
        if (role==1){
            QueryWrapper<Student> wrapper = new QueryWrapper<>();
            wrapper.eq("name",name).eq("pwd",pwd);
            one = ss.getOne(wrapper);
        }
        if (role==2){
            QueryWrapper<Teacher> wrapper = new QueryWrapper<>();
            wrapper.eq("name",name).eq("pwd",pwd);
            one = ts.getOne(wrapper);
        }
        if (role==3){
            QueryWrapper<Admin> wrapper = new QueryWrapper<>();
             wrapper.eq("name",name).eq("pwd",pwd);
             one = as.getOne(wrapper);
        }
        if (one!=null){
            session.setAttribute("user",one);
        }
        return one!=null;
    }
    //退出登录
    @GetMapping("/logout")
    public void logout(HttpSession session){
        session.invalidate();
    }

    //修改用户密码
    @PutMapping("/updatePwd")
    public void updatePwd(int role, String pwd, HttpSession session){
        if (role==1){
            Student student = (Student) session.getAttribute("user");
            student.setPwd(pwd);
            ss.updateById(student);
            session.setAttribute("user",student);
        }
        if (role==2){
            Teacher teacher = (Teacher) session.getAttribute("user");
            teacher.setPwd(pwd);
            ts.updateById(teacher);
            session.setAttribute("user",teacher);
        }
        if (role==3){
            Admin admin = (Admin) session.getAttribute("user");
            admin.setPwd(pwd);
            as.updateById(admin);
            session.setAttribute("user",admin);
        }
    }

}
